package com.geese.common;

import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;

import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;


@Service  
public class PropertiesService {
	private static Logger logger = LoggerFactory.getLogger(PropertiesService.class);
	
	private static final String EMPTY_STRING = "";
	private static final String SEPARATOR = "/";
	private static final String SUFFIX = ".properties";
	
	private String prefix ;
	private String[] fileNames = new String[]{"business_message"};
	
	private ImmutableMap<String, String> properties ;
	
	@Autowired
	public PropertiesService(Environment environment ) {
		this.prefix = getPrefix(environment);
		Map<String, String> tempMap = Maps.newHashMap();
		List<String> fileNameList = Arrays.asList(fileNames);
		for(String fileName : fileNameList) {
			StringBuilder pathBuilder = new StringBuilder();
			pathBuilder.append(SEPARATOR).append(this.prefix).append(SEPARATOR).append(fileName).append(SUFFIX);
			tempMap.putAll(Maps.fromProperties(getProperties(pathBuilder.toString())));
		}
		properties = ImmutableMap.copyOf(tempMap);
	}
	
	public String getProperty(String key) {
		if(StringUtils.isEmpty(key)) {
			return EMPTY_STRING;
		}
		return StringUtils.trimToEmpty(properties.get(key));
	}
	
	
	private String getPrefix(Environment environment) {
		if(ArrayUtils.isEmpty(environment.getActiveProfiles())) {
			return EMPTY_STRING;
		}
		return StringUtils.trimToEmpty(environment.getActiveProfiles()[0]);
	}
	
	private Properties getProperties(String path) {
		InputStream in = this.getClass().getClassLoader().getResourceAsStream(path);
		Properties properties = new Properties();
		try {
			properties.load(in);
		} catch (IOException e) {
			logger.error("file read error, path: " + path + " " + e.getMessage(), e);
		} finally {
			close(in);
		}
		return properties;
	}
	
	private void close(Closeable closeable) {
		if(closeable != null) {
			try {
				closeable.close();
			} catch (IOException e) {
			}
		}
	}

}
